#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Default handler. Loads main blog page."""

# Cruise Control
import base_handler

# Python
import logging

class Index(base_handler.BaseHandler):

  def Call(self):
    """Default handler. Called when user requests / or /index or /index.html"""
    posts_per_page = self.blog.posts_per_page

    # Verify user input
    page = self.params.get('page', default=1)
    try:
      page = abs(int(page))
    except ValueError:
      logging.error('index.py - Invalid page provided. Call: %s' % str(page))
      page = 1

    offset = (page - 1) * posts_per_page
    published_posts = self.db.GetPublishedPosts(offset, posts_per_page)

    self.html_vars['posts'] = published_posts
    self.html_vars['newer_posts'] = page - 1

    if published_posts.count() > (page * posts_per_page):
      self.html_vars['older_posts'] = page + 1

    self.html_vars['wups_no_posts'] = published_posts.count() <= offset
    self.SetMetaInfo(self.blog)
    self.RenderPage('index.html')
